// 3.2 轮询状态
use reqwest::Client;
use crate::api::get_stream_token::get_stream_token;
use crate::api::get_session_id::get_session_id;
use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use tokio::time::{sleep, Duration};

#[derive(Serialize, Deserialize, Debug)]
struct response {
    state: String,
}

pub async fn get_session_status() -> Result<()> {
    let client = Client::new();
    let session_id = get_session_id(None).await.unwrap();
    let url = format!("https://uks.core.gssv-play-prodxhome.xboxlive.com/v5/sessions/home/{}/state",session_id);
    let Authorization = format!("Bearer {}",get_stream_token().await.unwrap());

    loop {
        let response = client.get(&url)
        .header("Content-Type", "application/json")
        .header("Authorization", &Authorization)
        .send().await.unwrap();
        let response_code = response.status().as_u16();
        let response_text = response.text().await.unwrap();

        match  response_code{
            200 => {
                let response: response = serde_json::from_str(&response_text).unwrap();
                if(response.state == "Provisioned"){
                    println!("the session is provisioned, state: {}", response.state);
                    return Ok(());
                } else if response.state == "Failed" {
                    println!("the session failed to provision, state: {}", response.state);
                    return Err(anyhow!("the session failed to provision"));
                }
                else {
                    // 等待两秒后继续轮询
                    sleep(Duration::from_secs(2)).await;
                    println!("the session isn't provisioned, retrying...   state: {}", response.state);
                }
            }
            _ => {
                return Err(anyhow!("failed to get session status, code: {response_code}"));
            }
        }
    }

}